<template>
    <div class="common-container">
        <el-row class="top-actions" :gutter="10">
            <el-col :span="12" class="left-actions">
                <el-button type="success" @click="handleAdd">
                    <el-icon>
                        <Plus />
                    </el-icon>新增
                </el-button>
            </el-col>
            <el-col :span="12" class="right-actions">
                <el-button type="default" @click="handleRefresh">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    刷新
                </el-button>
            </el-col>
        </el-row>
        <div class="table-scroll-container">
            <el-table :data="tableData" stripe border style="width: 100%" v-loading="loading">
                <el-table-column prop="month" label="日期" />
                <el-table-column prop="htElectricitySettlementBillModelName" label="模板" />
                <el-table-column prop="sumPrice" label="结算金额" />
                <el-table-column label="操作" width="150">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="handleDetail(scope.row)">详情</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="pagination-container">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[15, 30, 45, 60, 100]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total" />
        </div>
        <el-dialog v-model="addDialogVisible" title="新增结算记录" width="500px" :before-close="handleAddDialogClose"
            :close-on-click-modal="false">
            <el-form ref="addFormRef" :model="addForm" label-width="100px" :rules="addFormRules">
                <el-form-item label="日期" prop="month">
                    <el-date-picker v-model="addForm.month" type="month" format="YYYY年MM月" value-format="YYYY-MM"
                        placeholder="选择月份" style="width: 100%" />
                </el-form-item>
                <el-form-item label="模板" prop="htElectricitySettlementBillModelId">
                    <el-select v-model="addForm.htElectricitySettlementBillModelId" placeholder="请选择模板"
                        style="width: 100%" clearable :disabled="modelList.length == 0">
                        <el-option v-for="model in modelList" :key="model.id" :label="model.name" :value="model.id" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="handleAddDialogClose">取消</el-button>
                <el-button type="primary" @click="handleAddSubmit" :loading="addLoading">确定</el-button>
            </template>
        </el-dialog>

        <el-dialog v-model="detailDialogVisible" :title="dialogTitle" width="95%"
            :before-close="handleDetailDialogClose">
            <div class="detail-base-info">
                <div class="base-info-title">厦门地铁运营有限公司</div>
                <div class="base-info-title">外单位用电结算清单</div>
                <div class="base-info-time">日期：{{ formatDate(new Date(), 4) }}</div>

                <el-row :gutter="30" class="info-row">
                    <el-col :span="24" class="info-col">
                        <div class="info-item">
                            <span class="info-label">客户名称：</span>
                            <span class="info-value">{{ detailData.customerName }}</span>
                        </div>
                    </el-col>
                </el-row>
                <el-row :gutter="30" class="info-row">
                    <el-col :span="24" class="info-col">
                        <div class="info-item">
                            <span class="info-label">项目名称：</span>
                            <span class="info-value">{{ detailData.projectName }}</span>
                        </div>
                    </el-col>
                </el-row>
                <el-row :gutter="30" class="info-row">
                    <el-col :span="24" class="info-col">
                        <div class="info-item">
                            <span class="info-label">合同编号及名称：</span>
                            <span class="info-value">{{ detailData.contractNoAndName }}</span>
                        </div>
                    </el-col>
                </el-row>
            </div>
            <div class="detail-table-container">
                <el-table :data="detailTableData" stripe border style="width: 100%"
                    :cell-style="{ 'text-align': 'center' }"
                    :header-cell-style="{ 'background-color': '#f5f7fa', 'font-weight': '600', 'text-align': 'center' }">
                    <el-table-column label="序号" width="80" align="center">
                        <template #default="scope">
                            <span v-if="scope.row.isTotalRow">总计</span>
                            <span v-else>{{ scope.$index + 1 }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="接用类型" width="100">
                        <template #default="scope">
                            <span v-if="scope.row.isTotalRow"></span>
                            <span v-else>{{ scope.row.connectionType }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="接用地点" width="140" :show-overflow-tooltip="{
                        popperClass: 'overflow-tooltip',
                    }">
                        <template #default="scope">
                            <span v-if="scope.row.isTotalRow"></span>
                            <span v-else>{{ scope.row.connectionLocation }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="结算起止时间" width="210">
                        <template #default="scope">
                            <span v-if="scope.row.isTotalRow"></span>
                            <span v-else>{{ scope.row.settlementDate }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="表计开始读数（kWh）" width="120">
                        <template #default="scope">
                            <span v-if="scope.row.isTotalRow"></span>
                            <span v-else>{{ scope.row.meterReadingStart }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="表计最终读数（kWh）" width="120">
                        <template #default="scope">
                            <span v-if="scope.row.isTotalRow"></span>
                            <span v-else>{{ scope.row.meterReadingEnd }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="用电结算用量（kWh）" width="120">
                        <template #default="scope">
                            <span v-if="scope.row.isTotalRow"></span>
                            <span v-else>{{ scope.row.settlementUsageKwh }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="结算单价（元/kWh）" width="120">
                        <template #default="scope">
                            <span v-if="scope.row.isTotalRow"></span>
                            <span v-else>{{ scope.row.htElectricityPrice }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="用电量结算金额（元）">
                        <template #default="scope">
                            <span v-if="scope.row.isTotalRow"></span>
                            <span v-else>{{ scope.row.settlementAmountElectricity }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="国网线损费用（元）">
                        <template #default="scope">
                            <span v-if="scope.row.isTotalRow"></span>
                            <span v-else>{{ scope.row.gridLineLoseFee }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="综合误差修正费用（元）">
                        <template #default="scope">
                            <span v-if="scope.row.isTotalRow"></span>
                            <span v-else>{{ scope.row.comprehensiveErrorCorrectionFee }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="结算电费（元）">
                        <template #default="scope">
                            <span class="total-amount">{{ scope.row.totalSettlementAmount }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" width="100" :show-overflow-tooltip="{
                        popperClass: 'overflow-tooltip',
                    }">
                        <template #default="scope">
                            {{ scope.row.remark }}
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="detail-base-info">
                <div class="info-note">
                    说明：用电量的单位为（千瓦时）。合计结算金额保留两位小数。
                </div>

                <div class="info-row">
                    甲方：{{ detailData.partyAName }}
                    / 乙方：{{ detailData.partyBName }}
                    <template v-if="detailData.partyCName !== null && detailData.partyCName !== undefined">
                        / 丙方：{{ detailData.partyCName }}
                    </template>
                </div>

                <div class="info-note">
                    说明
                    <span v-html="detailData.htElectricitySettlementBillModelRemark"></span>
                </div>

            </div>

            <template #footer>
                <el-button type="primary" :loading="submitLoading" @click="handleExport">导出</el-button>
            </template>
        </el-dialog>

    </div>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue';
import { Refresh, Plus } from '@element-plus/icons-vue';
import { ElMessage, ElForm, ElFormItem, ElLoading } from 'element-plus';
import { formatDate } from '@/utils/Format.js';
import htglAPI from '@/api/htgl.js';
import { ElMessageBox } from "element-plus";
import { errorNotify } from '@/utils/Misc';
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(15);
const total = ref(0);
const detailDialogVisible = ref(false);
const dialogTitle = ref('查看结算记录');
const submitLoading = ref(false);
const detailData = ref({});
const detailTableData = ref([]);
const detailDataId = ref('');
const addDialogVisible = ref(false);
const addLoading = ref(false);
const modelList = ref([]);
const addForm = ref({
    month: "",
    htElectricitySettlementBillModelId: ''
});
const addFormRules = ref({
    month: [
        { required: true, message: '请选择日期', trigger: 'change' }
    ],
    htElectricitySettlementBillModelId: [
        { required: true, message: '请选择模板', trigger: 'change' }
    ]
});
const addFormRef = ref(null);
const getLastMonth = () => {
    const currentDate = new Date();
    currentDate.setMonth(currentDate.getMonth() - 1);
    return formatDate(currentDate, 3);
};
const formatDateRange = (startDate, endDate) => {
    const formattedStart = formatDate(startDate, 2);
    const formattedEnd = formatDate(endDate, 2);
    return `${formattedStart} 至 ${formattedEnd}`;
};
const fetchData = () => {
    loading.value = true;
    const params = {
        pageDto: {
            pageNo: currentPage.value,
            pageSize: pageSize.value,
            orderBy: 'updated_at desc'
        },
    };
    htglAPI.listSettlementBill(params).then((res) => {
        tableData.value = res.data.page.list || [];
        tableData.value = tableData.value.map(item => ({
            ...item,
            month: item.month.split('-').join('年').replace("年0", "年") + '月'
        }))
        total.value = res.data?.page?.count || 0;
        loading.value = false;
    }).catch((error) => {
        errorNotify("QingDanShengCheng.vue", "fetchData", error);
        total.value = 0;
        loading.value = false;
    });
};
const formatRemark = (remark) => {
    let result = remark.replace(/(\d+\.)/g, '<br>$1');
    return result;
}
const getDetail = (id) => {
    const loading = ElLoading.service({
        lock: true,
        text: '生成结算单中...',
        background: 'rgba(0, 0, 0, 0.7)'
    });
    htglAPI.listSettlementBillDetail(id).then((res) => {
        detailData.value = res.data.htElectricitySettlementBillShowView || {};
        detailTableData.value = res.data.htElectricitySettlementBillShowView.htElectricitySettlementBillItemViewList || [];
        detailData.value.htElectricitySettlementBillModelRemark = formatRemark(detailData.value.htElectricitySettlementBillModelRemark)

        detailTableData.value = detailTableData.value.map(item => {
            const processedItem = Object.entries(item).reduce((acc, [key, value]) => {
                acc[key] = value === null || value === undefined ? "-" : value;
                return acc;
            }, {});
            return {
                ...processedItem,
                settlementDate: formatDateRange(item.settlementStartDate, item.settlementEndDate),
                htElectricityPrice: detailData.value.htElectricityPrice ?? "-",
                totalSettlementAmount: item.totalSettlementAmount.toFixed(4) ?? "-",
                remark: item.remark
            }

        });
        detailTableData.value.sort((a, b) => {

            const sortA = a.sortOrder ?? 0;
            const sortB = b.sortOrder ?? 0;
            return sortA - sortB;
        });
        addTotalRow()
        detailDialogVisible.value = true;

    }).catch((error) => {
        errorNotify("QingDanShengCheng.vue", "getDetail", error);
        detailData.value = {};
        detailTableData.value = [];
    }).finally(() => {
        loading.close();
    });
};
const addTotalRow = () => {
    if (!detailTableData.value.length) return;

    const isZhangZhou = detailData.value.projectName && detailData.value.projectName.includes('漳州');

    let totalAmount;
    if (isZhangZhou && detailTableData.value.length >= 3) {
        const firstAmount = Number(detailTableData.value[0].totalSettlementAmount) || 0;
        const secondAmount = Number(detailTableData.value[1].totalSettlementAmount) || 0;
        const thirdAmount = Number(detailTableData.value[2].totalSettlementAmount) || 0;
        totalAmount = firstAmount + secondAmount - thirdAmount;
    } else {
        totalAmount = detailTableData.value.reduce((sum, row) => {
            const amount = Number(row.totalSettlementAmount) || 0;
            return sum + amount;
        }, 0);
    }

    detailTableData.value.push({
        isTotalRow: true,
        totalSettlementAmount: totalAmount.toFixed(2),
    });
};
const fetchModelList = () => {
    htglAPI.listSettlementBillModel().then((res) => {
        modelList.value = res.data.page.list.sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'))

    }).catch((error) => {
        errorNotify("QingDanShengCheng.vue", "fetchModelList", error);
        modelList.value = [];
    });
};
onMounted(() => {
    fetchData();
});
const handleAdd = () => {
    if (addFormRef.value) {
        addFormRef.value.resetFields();
    }
    addForm.value.month = getLastMonth();
    addForm.value.htElectricitySettlementBillModelId = '';
    fetchModelList();
    addDialogVisible.value = true;
};
const handleAddSubmit = () => {
    addFormRef.value.validate((valid) => {
        if (valid) {
            addLoading.value = true;
            htglAPI.createSettlementBill(addForm.value).then((res) => {
                ElMessage.success('新增成功');
                addDialogVisible.value = false;
                fetchData();
            }).catch((error) => {
                console.error(error);
            }).finally(() => {
                addLoading.value = false;
            });
        }
    });
};
const handleAddDialogClose = () => {
    addDialogVisible.value = false;
};
const handleDetail = (row) => {
    getDetail(row.id);
    detailDataId.value = row.id;
};
const handleDelete = (row) => {
    ElMessageBox.confirm('将永久删除【' + row.month + '/' + row.htElectricitySettlementBillModelName + '】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        htglAPI.deleteSettlementBill(row.id).then((res) => {
            ElMessage.success("删除成功");
            fetchData();
        });
    }).catch(() => { });
};
const handleExport = () => {
    const loading = ElLoading.service({
        lock: true,
        text: '正在导出文件...',
        background: 'rgba(0, 0, 0, 0.7)'
    });
    htglAPI.exportSettlementBill(detailDataId.value)
        .then(response => {
            loading.close();
            const contentDisposition = response.headers['content-disposition'];
            let fileName = '结算单.xlsx';
            if (contentDisposition) {
                const match = contentDisposition.match(/filename=([^;]+)/);
                if (match && match[1]) {
                    fileName = decodeURIComponent(match[1].replace(/"/g, ''));
                }
            }
            const blob = new Blob([response.data], {
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = fileName;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            document.body.removeChild(a);
            ElMessage.success('导出成功');
        }).catch(error => {
            errorNotify("QingDanShengCheng.vue", "handleExport", error);
            loading.close();
        });
};
const handleDetailDialogClose = () => {
    detailDialogVisible.value = false;
    detailData.value = {};
    detailTableData.value = [];
};
const handleRefresh = () => {
    fetchData();
};
const handleSizeChange = (val) => {
    pageSize.value = val;
    fetchData();
};
const handleCurrentChange = (val) => {
    currentPage.value = val;
    fetchData();
};
</script>
<style scoped>
:deep(.overflow-tooltip) {
    width: 30%;
    font-size: 13px !important;
    border-radius: 4px !important;
    padding: 8px 12px !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
}

:deep(.el-dialog) {
    max-height: 90vh;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    margin-top: 2%;
}

:deep(.el-dialog__body) {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    max-height: calc(90vh - 100px);
}

.common-container {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    max-height: calc(100vh - 40px);
    display: flex;
    flex-direction: column;
}

.top-actions {
    margin-bottom: 20px;
    align-items: center;
}

.left-actions {
    text-align: left;
}

.right-actions {
    text-align: right;
}

.table-scroll-container {
    flex: 1;
    overflow-y: auto;
    margin-bottom: 20px;
    max-height: calc(100vh - 290px);
}

.table-scroll-container::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

.table-scroll-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.table-scroll-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}

.table-scroll-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

.pagination-container {
    margin-top: auto;
    padding-top: 10px;
    display: flex;
    justify-content: flex-end;
    position: sticky;
    bottom: 0;
    background-color: #fff;
    z-index: 10;
}

.base-info-title {
    text-align: center;
    font-weight: 700;
    font-size: 18px;
    line-height: 1.6;
    word-break: break-all;
}

.base-info-time {
    text-align: center;
}

.detail-base-info {
    margin-bottom: 8px;
    padding: 24px;
    background-color: #f8fafc;
    border-radius: 8px;
    border: 1px solid #e2e8f0;
    transition: all 0.3s ease;
}

.info-row {
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    transition: all 0.2s ease;
}

.info-row--highlight {
    background-color: #f0f7ff;
    padding: 12px 16px;
    border-radius: 6px;
}

.info-row:last-child {
    margin-bottom: 0;
}

.info-col {
    display: flex;
    align-items: center;
}

.info-item {
    width: 100%;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
}

.info-label {
    display: inline-block;
    width: 130px;
    color: #64748b;
    font-weight: 500;
    margin-right: 12px;
    font-size: 14px;
    text-align: right;
}

.info-value {
    color: #1e293b;
    word-break: break-all;
    font-size: 14px;
    line-height: 1.5;
}

.price-value {
    color: #2563eb;
    font-weight: 500;
}

.time-value {
    color: #64748b;
}

.total-sum {
    color: #dc2626;
    font-weight: 700;
    font-size: 16px;
}

.detail-table-section {
    margin-top: 12px;
}

.table-header {
    margin-bottom: 16px;
}

.table-header__title {
    font-size: 16px;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 8px;
}

.table-header__divider {
    height: 2px;
    width: 48px;
    background-color: #059669;
    border-radius: 1px;
}

.detail-table-container {
    overflow-x: auto;
    overflow-y: auto;
    border-radius: 8px;
    border: 1px solid #e2e8f0;
    transition: all 0.3s ease;
    margin-bottom: 8px;
}

.detail-table-container:hover {
    box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.03);
}

.detail-table-container::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

.detail-table-container::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 4px;
}

.detail-table-container::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 4px;
    transition: background 0.2s ease;
}

.detail-table-container::-webkit-scrollbar-thumb:hover {
    background: #94a3b8;
}

.el-table__cell {
    padding: 14px 12px !important;
    font-size: 14px;
    color: #1e293b;
}

.el-table__header th {
    background-color: #f1f5f9 !important;
    color: #475569 !important;
    font-weight: 600 !important;
    border-bottom: 1px solid #e2e8f0 !important;
}

.total-amount {
    color: #2563eb;
    font-weight: 600;
    font-size: 14px;
}


.info-note {
    text-align: left;
    margin-bottom: 8px;
    font-weight: 500;
}
</style>